<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\SarsUser;
use App\Repository\SarsUserRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiSarsUserController extends BaseController4Restful
{
    /**
     * @Route("/api/sarsUsers", name="apiGetSarsUsers",methods={"GET","POST"})
     */
    public function apiGetSarsUsers(SarsUserRepository $repository, Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $adminId = $this->needToBeAdmin();
                $data = $this->getRequestData();
                /**@var $SarsUser SarsUser */
                $SarsUser = $this->createEntity($data, SarsUser::class);
                $SarsUser->setCreateBy($adminId);
                $idcode = $SarsUser->getShenfenzhenghao();
                if ($findUser = $repository->findOneBy(array("shenfenzhenghao" => $idcode))) {
                    return $this->json_out(201, "身份证号{$idcode}用户已存在");
                }

                $SarsUser->setDengjiriqi(date($this->YYMMDDHHIISS));
                $this->myEm()->persist($SarsUser);
                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $SarsUser);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array(), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/sarsUsers/{id}", name="apiAddSarsUsers",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateSarsUsers(SarsUser $SarsUser, Request $request, SarsUserRepository $repository)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($SarsUser);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                /**@var $SarsUser SarsUser */
                $SarsUser = $this->updateEntity($data, SarsUser::class, $SarsUser);
                $idcode = $SarsUser->getShenfenzhenghao();
                if ($findUser = $repository->findOneBy(array("shenfenzhenghao" => $idcode))) {
                    return $this->json_out(0, "身份证号{$idcode}用户已存在");
                }
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($SarsUser);
        $this->myEm()->flush();
        return $this->json_out(200, "获取成功", $SarsUser);
    }
}
